import os
import re
import sys
import threading

from PySide6.QtGui import QFont
from PySide6.QtWidgets import QMainWindow, QHeaderView, QTableWidgetItem, QMessageBox

from file_py.SqlHelper import SqlHelper
from ui.main_ui import Ui_MainWindow
from file_py.file_operations import FileManager
from file_py.user import Useradmin
from file_py.update_user import UpdateUser
from file_py.common import Variable
from playsound import playsound
import pyttsx3
from tkinter import messagebox as msgbox
import pandas as pd


class MainWindow(QMainWindow):  # 主窗口
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.fileManager = FileManager()
        if Variable.user_zd['privs'] == 0:  # 设置非管理员权限
            self.ui.action_add.setVisible(False)
            self.ui.action_update.setVisible(False)
            self.ui.action_delete.setVisible(False)
            self.ui.user_adm.setVisible(False)
        self.engine = pyttsx3.init()
        self.sqlHelper = SqlHelper()

        self.df = self.sqlHelper.Query_SQLServer_by_SQL(f"SELECT cpn,ipn FROM Webasto")
        if self.df.empty:
            msgbox.showerror('错误提示', '请先导入数据，然后重启程序')
        self.df['cpn'] = self.df['cpn'].str.lower()
        self.df['ipn'] = self.df['ipn'].str.lower()
        self.mp3falg = True  # True播放女声，False播放男声
        self.bind()
        self.getmp3path()

    def getmp3path(self):
        self.success = os.path.join(Variable.path, 'success.wav')
        self.fail = os.path.join(Variable.path, 'fail.wav')
        self.m1 = os.path.join(Variable.path, 'm1.mp3')
        self.m2 = os.path.join(Variable.path, 'm2.mp3')
        self.m3 = os.path.join(Variable.path, 'm3.mp3')
        self.m4 = os.path.join(Variable.path, 'm4.mp3')
        self.m11 = os.path.join(Variable.path, 'm11.mp3')
        self.m21 = os.path.join(Variable.path, 'm21.mp3')
        self.m31 = os.path.join(Variable.path, 'm31.mp3')
        self.m41 = os.path.join(Variable.path, 'm41.mp3')

    def bind(self):
        self.ui.action_add.triggered.connect(self.fileManager.add)  # 添加
        self.ui.action_update.triggered.connect(self.fileManager.update)  # 修改
        self.ui.action_delete.triggered.connect(self.fileManager.delete)  # 删除
        self.ui.action_query.triggered.connect(self.fileManager.export)  # 导出数据
        self.ui.query_data.triggered.connect(self.fileManager.querydata)  # 查询数据
        self.ui.action_match.triggered.connect(self.fileManager.match)  # 匹配
        self.ui.txtScan.returnPressed.connect(self.on_return_pressed)  # 回车键查询
        self.ui.user_adm.triggered.connect(self.userFrom)
        self.ui.pwd_update.triggered.connect(self.update_userFrom)
        # self.ui.rab_woman点击事件
        self.ui.rab_man.clicked.connect(self.on_radio_button_clicked)
        self.ui.rab_woman.clicked.connect(self.on_radio_button_clicked)

    def on_radio_button_clicked(self):
        if self.ui.rab_woman.isChecked():
            self.mp3falg = True
        else:
            self.mp3falg = False

    def userFrom(self):
        self.ui.useradmin = Useradmin()
        self.ui.useradmin.show()

    def update_userFrom(self):
        self.ui.updateUser = UpdateUser()
        self.ui.updateUser.show()

    def play_mp3(self, file_name):
        playsound(file_name)

    def say_text(self, text):
        self.engine.say(text)
        self.engine.runAndWait()

    def InsertData(self, sql):
        self.sqlHelper.delete_from_sql(sql)

    def on_return_pressed(self):
        try:
            user_input = self.ui.txtScan.text().strip()  # 获取用户输入的内容
            if user_input == "":
                return
            if user_input == '123456':
                Variable.flag = True
                if self.mp3falg:
                    t = threading.Thread(target=self.play_mp3, args=(self.m1,))  # 请扫描客户零件号
                else:
                    t = threading.Thread(target=self.play_mp3, args=(self.m11,))
                t.start()

                return
            user_input = user_input.lower()
            if Variable.flag:  # 如果正在等待扫描客户零件号
                for cp in self.df['cpn']:
                    if cp in user_input:
                        Variable.cpn = cp
                        Variable.ipn = self.df.loc[self.df['cpn'] == cp, 'ipn'].values[0]
                        break
                if Variable.ipn == '':
                    if self.mp3falg:
                        t = threading.Thread(target=self.play_mp3, args=(self.m2,))  # 您扫描的客户零件号不存在
                    else:
                        t = threading.Thread(target=self.play_mp3, args=(self.m21,))
                    t.start()
                    return

                # 使用正则表达式匹配目标部分

                # for reg in Variable.regs:
                #     match = re.search(reg, user_input)
                #     if match:
                #         cp = match.group(1)
                #         break
                # if cp=='':
                #     t = threading.Thread(target=self.say_text, args=("未能解析出数据,请扫描正确格式的二维码",))
                #     t.start()
                #     return
                # Variable.ipn = self.sqlHelper.Query_SQLServer_by_SQL(f"SELECT ipn,ordernum FROM Webasto WHERE cpn='{cp}'")
                # if Variable.ipn.empty:
                #     t = threading.Thread(target=self.say_text, args=("您扫描的客户零件号不存在",))
                #     t.start()
                #     return
                # else:
                Variable.flag = False
                self.ui.lab_cpn.setText(Variable.cpn)
                self.ui.lab_ipn.setText(Variable.ipn)
                if self.mp3falg:
                    t = threading.Thread(target=self.play_mp3, args=(self.m3,))  # 请扫描内部零件号
                else:
                    t = threading.Thread(target=self.play_mp3, args=(self.m31,))
                t.start()


            else:  # 如果正在等待扫描内部零件号
                if user_input == Variable.ipn:
                    t = threading.Thread(target=self.play_mp3, args=(self.success,))  # 播放成功提示音
                    t.start()
                    Variable.flag = True
                    t1 = threading.Thread(target=self.InsertData, args=(
                        f"insert into Operation(cpn,ipn) values('{Variable.cpn}','{Variable.ipn}')",))
                    t1.start()

                else:
                    if self.mp3falg:
                        t = threading.Thread(target=self.play_mp3, args=(self.m4,))  # 请扫描正确的内部零件号
                    else:
                        t = threading.Thread(target=self.play_mp3, args=(self.m41,))
                    t.start()
        except Exception as e:
            QMessageBox.warning(self, '警告', '程序出现异常！' + str(e))
        finally:
            self.ui.txtScan.clear()
            # 获取焦点
            self.ui.txtScan.setFocus()
            if Variable.flag:
                Variable.ipn = ''
                Variable.cpn = ''
                self.ui.lab_cpn.setText('')
                self.ui.lab_ipn.setText('')
                self.ui.txtScan.setPlaceholderText('请扫描客户零件号')
            else:
                self.ui.txtScan.setPlaceholderText('请扫描内部零件号')